package helper

import (
	"bytes"
	"crypto/md5"
	"encoding/hex"
	"gopkg.in/kataras/iris.v6"
	"math/rand"
	"os"
	"regexp"
	"strings"
	"time"
	"github.com/kataras/go-mailer"
)

const (
	RANDOM_ONLYINT = "0123456789"
	RANDOM_ONLYSTR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	RANDOM_ALL     = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~!@#$%^&*()_+-={}[],./?><*."
)

//var ossClient *oss.Client

//随机字符串
func GetRandomStr(strlen int64, randomType string) string {
	buf := bytes.Buffer{} //创建字符串拼接buffer对象
	//播种随机种子按照纳秒时间戳 不调用会得到固定值
	var seed []byte
	var i int64
	seed = []byte(randomType)
	length := len(seed)
	rand.Seed(time.Now().UnixNano())
	for i = 0; i < strlen; i++ {
		pos := rand.Intn(length)
		buf.WriteString(string(seed[pos]))
	}
	return buf.String()
}

//时间戳
func GetTimeStamp() int64 {
	return time.Now().Unix()
}

// 随机字符串 size 长度 随机字符串
func Krand(size int, kind int) []byte {
	ikind, kinds, result := kind, [][]int{{10, 48}, {26, 97}, {26, 65}}, make([]byte, size)
	is_all := kind > 2 || kind < 0
	//随机种子
	rand.Seed(time.Now().UnixNano())
	for i := 0; i < size; i++ {
		if is_all {
			ikind = rand.Intn(3) // random ikind
		}
		scope, base := kinds[ikind][0], kinds[ikind][1]
		result[i] = uint8(base + rand.Intn(scope))
	}
	return result
}

//验证邮箱
func VerifyEmail(email string) bool {
	matched, _ := regexp.MatchString("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$", email)
	return matched
}

func VerifyInt(number string) bool {
	matched, _ := regexp.MatchString("^[0-9]+$", number)
	return matched
}

//获取登陆用户的Session
func GetLoginId(this *iris.Context) (int64, error) {
	return this.Session().GetInt64("login_userid")
}

func VerifyFloat(floatNumber string) bool {
	matched, _ := regexp.MatchString("[0-9]+.[0-9]+", floatNumber)
	return matched
}

func FormatTime(sec int64) string {
	timeStamp := time.Unix(sec, 0)
	return timeStamp.Format("2006-01-02 03:04:05")
}

//当前时间 Y m d H:i:s
func NowDate(str string) string {
	t := time.Now().UTC()
	str = strings.Replace(str, "Y", "2006", 1)
	str = strings.Replace(str, "m", "01", 1)
	str = strings.Replace(str, "d", "02", 1)
	str = strings.Replace(str, "H", "13", 1)
	str = strings.Replace(str, "i", "04", 1)
	str = strings.Replace(str, "s", "05", 1)
	return t.Format(str)
}

//md5加密字符串
func GetMd5(str string) string {
	md_ := md5.New()
	md_.Write([]byte(str))
	return hex.EncodeToString(md_.Sum(nil))
}

func FileExists(path string) (bool, error) {
	fs, err := os.OpenFile(path, os.O_RDONLY, os.ModePerm)
	if err != nil {
		return false, err
	}
	fs.Close()
	return true, nil
}

func SendEmail(title, url string, to []string, this *iris.Context) error {
	mailService := mailer.New(mailer.Config{
		Host:     "smtp.163.com",
		Username: "chenchengbin92@163.com",
		Password: "irislayim2017",
		Port:     25,
	})
	content := `
<style>
    .main{width:655px;margin:0px auto;border: 2px solid #0382db;background-color:#f8fcff;}
    .main-box{ padding:15px;}
    .mail-title{ font-size:15px; color:#ffffff; background-color:#0382db; font-weight:bold; padding:0px 0px 0px 15px;height:80px;line-height:80px;}
    .fontstyle{ color:#be0303; font-weight:bold;}
    .a-link{ color:#0078ff; font-weight:bold;}
    .csdn{ text-align:right; color:#000000; font-weight: bold;}
    .csdn-color{ color:#000000; font-weight: bold; padding-top:20px;}
    .logo-right{float:right;display:inline-block;padding-right:15px;}
</style>
<div class="main">
    <div class="mail-title">亲爱的用户</div>
    <div class="main-box">
        <p>` + title + `<br/>
            <a href="` + url + `" class="a-link" target="_blank">` + url + `</a>
            <br/>如果链接点击无效，请将链接复制到您的浏览器中继续访问。</p>
        <p class="csdn csdn-color">Iris Layim版</p>
    </div>
</div>`
	return mailService.Send(title, content, to...)
}
